import Weibos from '../MyBlog/RightContainer/Weibo/';
import BlogApi from '../../apis/myBlog';
import { message,Modal } from 'antd';
import WeaWhitePage from './wea-white-page/';
import WeaUtils from './wea-utils'
const {GetRegex} = WeaUtils

class WeiboListNR extends React.Component {
	constructor(props) {
		super(props);
		let funcs = ['setScore', 'editComment', 'editAgree', 'editWeibo', 'getSystemWorkLog','getBasicInfo',
            'deleteComment', 'getDefaultTemplate'];
		funcs.forEach((func) => this[func] = this[func].bind(this));
		this.state = {
			defaultTemplate: {},
			records: props.records,
            weiboCKEditorConfig: [],
			userInfo: {
				currentUser: {
					id: props.currentUserId
				}
			}
		};
	}
	componentDidMount() {
	    BlogApi.getWeiboCKEditorConfig().then(result => {
	        this.setState({
                weiboCKEditorConfig: result.appList
            });
        }).catch(error => message.error(error));
	    // 如果是我的微博，则可以发表微博，需要取默认模板。
	    if (this.props.userId == this.props.currentUserId)
    		this.getDefaultTemplate();
	}
	
	componentWillReceiveProps(nextProps) {
	    this.setState({
	        records: nextProps.records
        });
    }
	
	getDefaultTemplate() {
		BlogApi.getDefaultTemplate().then(
			result => this.setState({defaultTemplate: result.defaultTemplate || {}})
		).catch(error => {message.error(error)});
	}
	
	
    
    /**
	 * 原意是在发表微博时处理左侧信息。保留此接口，用于发表新微博时的回调。
	 * @param params
	 */
	getBasicInfo(params){
		this.props.publishWeiboCallback && this.props.publishWeiboCallback(params);
	}
	
	setReaded(params,others) {
		BlogApi.setReaded(params).then(
			result => {
				let records = replaceWeiboList(others, "", "blogDiscussVo", this.state.records, result);
				this.setState({
					records: records
				});
			}
		).catch(error => {message.error(error)});
	}
	setScore(params){
		BlogApi.setScore(params).then(
			result => {
				message.success("操作成功！")
				let records = replaceWeiboList(params, "", "blogDiscussVo", this.state.records, result);
				this.setState({
					records: records
				});
			}
		).catch(error => {message.error(error)});
	}
	editComment(params,others){
        if (params.content) {
            params.content = params.content.replace(GetRegex('wrap'), "")
            BlogApi.editComment(params).then(
                result => {
                    message.success("操作成功！")
                    let records = replaceWeiboList(others, "blogReplyList", "blogReplyList", this.state.records, result);
                    this.setState({
                        records: records
                    });
                }
            ).catch(error => {
                message.error(error)
            });
        } else {
            Modal.warning({title: '警告', content: "请填写内容"});
        }
	}
	editAgree(params,others){
		BlogApi.editAgree(params).then(
			result => {
				message.success("操作成功！")
				let records = replaceWeiboList(others, "blogZanBean", "blogZanBean", this.state.records, result)
				this.setState({
					records: records
				});
			}
		).catch(error => {message.error(error)});
	}
	
	// weibo的action中还有一个callback，但callback是用来刷新basicInfo的，所以不要了。
	editWeibo(params,others){
        if (params.content) {
            params.content = params.content.replace(GetRegex('wrap'), "")
            BlogApi.editWeibo(params).then(
                result => {
                    message.success("操作成功！")
                    let records = replaceWeiboList(others, "", "blogDiscussVo", this.state.records, result)
                    this.setState({
                        records: records
                    });
                }
            ).catch(error => {message.error(error)});
        } else {
            Modal.warning({title: '警告', content: "请填写内容"})
        }
	}
	
	getSystemWorkLog(params,others){
		BlogApi.getSystemWorkLog(params).then(
			result => {
                let records = replaceWeiboList(others, "sysWorkLog", "sysWorkLog", this.state.records, result);
                this.setState({
                    records: records
                });
            }
            
		).catch(error => {message.error(error)});
	}
	
	deleteComment(params,others){
		BlogApi.deleteComment(params).then(
			result => {
				message.success("操作成功！")
				let records = replaceWeiboList(others, "blogReplyList", "replyList", this.state.records, result);
				this.setState({
					records: records
				});
			}
		).catch(error => {message.error(error)});
	}
    
    remind(params, callback) {
        BlogApi.setNotice(params).then(
            result=> {
                message.info("已发送提醒");
                callback && callback(result);
            }
        ).catch(
            error => {
                message.error(error)
            }
        );
    }
	render() {
		let {userInfo, records, defaultTemplate,weiboCKEditorConfig} = this.state;
		let hasEditor = this.props.userId == this.props.currentUserId;
        if (!hasEditor && (!records || !records.discussList || records.discussList.length == 0))
            return <WeaWhitePage />;
		return (
            <Weibos
                actions={this}
                defaultTemplate = {defaultTemplate}
                records={records}
                blogType={this.props.blogType}
                hasScroll={this.props.hasScroll}
                hasEditor={hasEditor}
                hasImage={this.props.hasImage}
                userInfo={userInfo}
                weiboCKEditorConfig={weiboCKEditorConfig}
                height={this.props.height}
            />
		);
	}
}
const replaceWeiboList = (others, _old, _new, records, data) => {
    let weiboList = Object.assign({},records);
    if (weiboList.discussList && weiboList.discussList.length > 0) {
        weiboList.discussList.forEach((item, key) => {
            let isThis = others.discussId ? item.id == others.discussId :
                others.userId ? (item.workdate == others.workdate && item.userid == others.userId) :
                item.workdate == others.workdate;
            if (isThis) {
                if (_old)  {
                    weiboList.discussList[key][_old] = data[_new];
                } else {
                    weiboList.discussList[key] = data[_new];
                }
            }
        });
    } else {
        weiboList.discussList.push(data[_new]);
    }
    return weiboList;
}
WeiboListNR.propTypes = {
    userId: React.PropTypes.string,//查看用户id
	height: React.PropTypes.string,//声明定高
    records: React.PropTypes.object,//展示的数据
	currentUserId: React.PropTypes.string,//登录用户id
	blogType: React.PropTypes.any,//用于生成CKEditor的唯一标识
	hasScroll: React.PropTypes.bool,//是否显示时间轴
	hasImage: React.PropTypes.bool,//是否显示头像
	publishWeiboCallback: React.PropTypes.func//发表微博时的回调
};
WeiboListNR.defaultProps = {
	blogType: 100,
	hasScroll: true,
	hasImage: true,
    height: 'auto'
};

export default WeiboListNR;